require 'apr.StringBuffer'
require 'moonunit'

test_stringbuffer = moonunit.TestCase:new()

function test_stringbuffer:test_simple()
    local buf = apr.StringBuffer.new()
    assert(buf.pos == 0)
    buf:write('hello')
    buf:write(' ')
    buf:write('world!')
    assert(buf:getvalue() == 'hello world!')
    assert(buf:read(1) == nil)
    buf:seek('set', 1)
    assert(buf:read(4) == 'ello')
end

function test_stringbuffer:test_seek()
    local buf = apr.StringBuffer.new()
    buf:write('hello')
    buf:write(' ')
    buf:write('world!')
    
    assert(buf:seek() == 12)
    assert(buf:seek('set') == 0)
    assert(buf:seek() == 0)
    assert(buf:seek('cur', 2) == 2)
    assert(buf:seek() == 2)
    assert(buf:seek('end') == 12)
    assert(buf:seek('cur', -4) == 8)
    assert(buf:read(4) == 'rld!')
end

function test_stringbuffer:test_readformat()
    local buf = apr.StringBuffer.new("line1\nline2\nline3\n1234abc")
    buf:seek('set')
    assert(buf:read() == 'line1')
    buf:seek('set')
    assert(buf:read(5) == 'line1')
    buf:seek('set')
    assert(buf:read('*l') == 'line1')
    buf:seek('set')
    assert(buf:read(5, 1, '*l', '*l', '*a') == 'line1', '\n', 'line2', 'line3', '1234abc')
    buf:seek('end', -7)
    assert(buf:read('*n') == 1234)
    assert(buf:read('*l') == 'abc')
end

function test_stringbuffer:test_readlines()
    local buf = apr.StringBuffer.new("line1")
    buf:write("\nline2\n")
    buf:write("line3")
    for line in buf:lines() do
        assert(line == 'line1' or line == 'line2' or line == 'line3')
    end
end

function test_stringbuffer:test_startval()
    local buf = apr.StringBuffer.new('testval')
    assert(buf:getvalue() == 'testval')
    assert(buf.pos == 7)
    buf:write('2')
    assert(buf.pos == 8)
    assert(buf:getvalue() == 'testval2')
end
